package com.burger.burgerpicturebackend.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burger.burgerpicturebackend.annotation.AuthCheck;
import com.burger.burgerpicturebackend.common.BaseResponse;
import com.burger.burgerpicturebackend.common.DeleteRequest;
import com.burger.burgerpicturebackend.common.ResultUtils;
import com.burger.burgerpicturebackend.constant.UserConstant;
import com.burger.burgerpicturebackend.exception.BusinessException;
import com.burger.burgerpicturebackend.exception.ErrorCode;
import com.burger.burgerpicturebackend.exception.ThrowUtils;
import com.burger.burgerpicturebackend.model.dto.tags.TagsAddRequest;
import com.burger.burgerpicturebackend.model.dto.tags.TagsQueryRequest;
import com.burger.burgerpicturebackend.model.entity.Tags;
import com.burger.burgerpicturebackend.model.entity.Tags;
import com.burger.burgerpicturebackend.model.entity.User;
import com.burger.burgerpicturebackend.service.TagsService;
import com.burger.burgerpicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 标签接口
 *
 */
@RestController
@RequestMapping("/tags")
@Slf4j
@CrossOrigin
public class TagsController {

    @Resource
    private TagsService tagService;

    @Resource
    private UserService userService;

    @PostMapping("/addTags")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<String> addTags(TagsAddRequest tagsAddRequest, HttpServletRequest request) {
        Tags tags = new Tags();
        String tagName = tagsAddRequest.getTagName();
        tags.setTagName(tagName);
        tagService.save(tags);
        return ResultUtils.success(tagName);
    }


    @GetMapping("/get/tags")
    public BaseResponse<List<Tags>> getTags(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        if (user==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录，请先登录");
        }
        QueryWrapper<Tags> queryWrapper = new QueryWrapper<>();
        List<Tags> tagList = tagService.list(queryWrapper);
        return ResultUtils.success(tagList);
    }

    /**
     * 记录标签使用次数
     */
    @PostMapping("/record")
    public BaseResponse<Boolean> recordTags(@RequestBody TagsAddRequest tagsAddRequest, HttpServletRequest request) {
        QueryWrapper<Tags> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tagName", tagsAddRequest.getTagName());
        Tags tags = tagService.getOne(queryWrapper);
        tags.setUsageCount(tags.getUsageCount() + 1);
        tagService.updateById(tags);
        return ResultUtils.success(true);
    }

    /**
     * 返回热门标签
     */
    @GetMapping("/hotTags")
    public BaseResponse<List<Tags>> hotTags(HttpServletRequest request) {
        QueryWrapper<Tags> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("usageCount");
        queryWrapper.last("limit 10");
        List<Tags> tagList = tagService.list(queryWrapper);
        return ResultUtils.success(tagList);
    }

    /**
     * 分页获取标签列表（仅管理员可用）
     */
    @PostMapping("/search/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Tags>> listTagsByPage(@RequestBody TagsQueryRequest tagsQueryRequest) {
        long current = tagsQueryRequest.getCurrent();
        long size = tagsQueryRequest.getPageSize();
        // 查询数据库
        Page<Tags> tagsPage = tagService.page(new Page<>(current, size)
                , tagService.getQueryWrapper(tagsQueryRequest));
        return ResultUtils.success(tagsPage);
    }

    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteTag(@RequestBody DeleteRequest deleteRequest
            , HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = deleteRequest.getId();
        // 判断是否存在
        Tags oldTag = tagService.getById(id);
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = tagService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
}
